package com.zhhs.galaxyott.adapters;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.zhhs.galaxyott.R;
import com.zhhs.galaxyott.activity.moreMoviesActivity.MoreMoviesActivity;
import com.zhhs.galaxyott.activity.moreMoviesActivity.MoreMoviesHolder;
import com.zhhs.galaxyott.beans.CategoryBean;
import com.zhhs.galaxyott.beans.CategoryMoviesBean;
import com.zhhs.galaxyott.http.api.RequestMaker;
import com.zhhs.galaxyott.httpVolley.base.ResponseListener;
import com.zhhs.galaxyott.httpVolley.response.CategoryMoviesResponse;
import com.zhhs.galaxyott.utils.Logs;

public class MoviesPagersAdapter extends PagerAdapter {

    private static Context mContext;
    private static List<View> list = new ArrayList<View>();
    private static List<CategoryBean> mlistData = new ArrayList<CategoryBean>();
    private static List<CategoryMoviesBean> PagerData = new ArrayList<CategoryMoviesBean>();
    private View view;
    private static MoreMoviesAdapter mAdapter;
    private static int pageNo;
    private static int pageRow;
    private static int countPage;
    private static int posSelect;
    private static final int NUMPERPAGE = 15;

    private static GridView mGridViews;
    private static GridView mGridView;
    public static int curpageItem;

    public MoviesPagersAdapter(Context mContext, List<View> list, List<CategoryBean> mlistData) {
        this.mContext = mContext;
        this.list = list;
        this.mlistData = mlistData;

    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Logs.logD("DEBUG_DT", "destroyItem-->" + position);
        container.removeView(list.get(position));
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        list.get(position).setTag(position);

        container.addView(list.get(position));// 实例化页卡

        Logs.logD("DEBUG_DT", "THIS IS instantiateItem-->instantiateItem");

        // loadData(position, mlistData.get(position).getId(), 1, NUMPERPAGE);

        return list.get(position);
    }

    @Override
    public int getItemPosition(Object object) {
        // TODO Auto-generated method stub
        View view = (View) object;
        if (MoreMoviesActivity.selectId == (Integer) view.getTag()) {
            return POSITION_NONE;
        } else {
            return POSITION_UNCHANGED;
        }
        // return super.getItemPosition(object);
    }

    private void loadData(final int pos, int index, int page, int num) {

        final int categoryid = index;
        pageNo = page;
        pageRow = num;

        RequestMaker.getCategoryMovie((Activity) mContext, categoryid, pageNo, pageRow,
                new ResponseListener<CategoryMoviesResponse>() {

                    @Override
                    public void onResponse(CategoryMoviesResponse result) {
                        // if (result.Beans == null || result.Beans.size() == 0)
                        // {
                        // return;
                        // }

                        Logs.logD("DEBUG_DT",
                                "THIS IS getCategoryMovie-->" + result.errCode + "size" + result.Beans.size()
                                        + "categoryid" + categoryid + "count:" + result.getPageCount());

                        if (result.errCode == 0) {
                            countPage = result.getPageCount();

                            PagerData = result.Beans;

                            curpageItem = PagerData.size();

                            initGridView(pos, PagerData);

                        }

                    }

                    @Override
                    public void onError(VolleyError error) {

                    }
                });

    }

    private static void refreshLoadData(final int pos, int index, int page, int num) {

        final int categoryid = index;
        pageNo = page;
        pageRow = num;

        RequestMaker.getCategoryMovie((Activity) mContext, categoryid, pageNo, pageRow,
                new ResponseListener<CategoryMoviesResponse>() {

                    @Override
                    public void onResponse(CategoryMoviesResponse result) {

                        Logs.logD("DEBUG_DT",
                                "THIS IS getCategoryMovie-->" + result.errCode + "size" + result.Beans.size()
                                        + "categoryid" + categoryid);
                        if (result.errCode == 0) {

                            PagerData.addAll(result.Beans);

                            curpageItem = PagerData.size();

                            mAdapter.notifyDataSetChanged();
                            Logs.logD("DEBUG_DT", "THIS IS getCategoryMovie-->curpageItem" + curpageItem);
                        }

                    }

                    @Override
                    public void onError(VolleyError error) {

                    }
                });

    }

    public void initViews(int position) {
        posSelect = position;
        loadData(position, mlistData.get(position).getId(), 1, NUMPERPAGE);
    }

    private void initGridView(final int postion, List<CategoryMoviesBean> PagerData) {
        view = list.get(postion);

        // view.setId(postion);

        mGridViews = (GridView) view.findViewById(R.id.gv_movies);

        mAdapter = new MoreMoviesAdapter(mContext, PagerData);

        mGridViews.setAdapter(mAdapter);

        // if (!MoreMoviesActivity.isFirstLoad) {
        // Logs.logD("DEBUG_IN", "THIS IS initGridView-->");
        // MoreMoviesActivity.detailFocus = true;
        // mGridView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
        // mGridView.requestFocus();
        //
        // } else {
        // MoreMoviesActivity.detailFocus = true;
        // mGridView.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        // mGridView.requestFocus();
        // }
        mGridViews.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

        /*********** 方案二 ************/
        // mGridViews.getViewTreeObserver().addOnGlobalLayoutListener(new
        // OnGlobalLayoutListener() {
        // @Override
        // public void onGlobalLayout() {
        // MoreMoviesHolder.mListView.getChildAt(postion).requestFocus();
        //
        // }
        // });
        /*********** end ************/
    }

    @Override
    public boolean isViewFromObject(View v, Object object) {
        return v == object;// 官方推荐
    }

    public static int index = 0;

    /*********************** 方案一 *****************************/
    // for DirectionalViewPager
    // public static synchronized boolean onKeyDown(int pos, int keyCode,
    // KeyEvent event) {
    //
    // if (PagerData == null || PagerData.size() == 0) {
    // return true;
    // }
    //
    // mGridView = (GridView) list.get(pos).findViewById(R.id.gv_movies);
    //
    // switch (keyCode) {
    // case KeyEvent.KEYCODE_DPAD_RIGHT:
    //
    // if (mGridView.getCount() == 0) {
    // return true;
    // }
    // Logs.logD("DEBUG", "THIS IS onKeyDown-->0" + mGridView.hasFocus());
    // if (MoreMoviesActivity.detailFocus == true) {
    // Logs.logD("DEBUG_1", "THIS IS onKeyDown--test>1" + index);
    //
    // if ((index + 1) % 5 != 0 && index < PagerData.size() - 1) {
    // index++;
    // if (mGridView.getChildAt(index) != null) {
    // mGridView.getChildAt(index).requestFocus();
    // } else {
    // if (mGridView.getChildAt(index--) != null)
    // mGridView.getChildAt(index).requestFocus();
    //
    // }
    //
    // return true;
    // } else {
    // if (mGridView.getChildAt(index) != null) {
    // mGridView.getChildAt(index).requestFocus();
    // }
    // return true;
    // }
    //
    // } else {
    // index = 0;
    // Logs.logD("DEBUG_1", "THIS IS onKeyDown-->2");
    // MoreMoviesActivity.detailFocus = true;
    // mGridView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
    // if (mGridView.getChildAt(index) != null) {
    // mGridView.getChildAt(index).requestFocus();
    // }
    // Logs.logD("DEBUG_1", "THIS IS onKeyDown-->3");
    //
    // return true;
    // }
    // // break;
    //
    // case KeyEvent.KEYCODE_DPAD_LEFT:
    // if (mGridView.findFocus() != null && isLeftView()) {
    // Logs.logD("DEBUG_1", "THIS IS onKeyDown-->KEYCODE_DPAD_LEFT");
    // MoreMoviesActivity.detailFocus = false;
    // mGridView.setDescendantFocusability(GridView.FOCUS_BLOCK_DESCENDANTS);
    // mGridView.clearFocus();
    // } else if (MoreMoviesActivity.detailFocus == true) {
    // Logs.logD("DEBUG_1", "THIS IS onKeyDown--test>1" + index);
    //
    // if (index % 5 != 0 && index > 0) {
    // index--;
    // }
    // // 这种强制设置焦点容易报错
    // if (mGridView.getChildAt(index) != null) {
    // mGridView.getChildAt(index).requestFocus();
    // }
    // return true;
    // }
    // break;
    //
    // case KeyEvent.KEYCODE_DPAD_DOWN:
    // Logs.logD("DEBUG_1", "THIS IS onkeydown--test>");
    // if (MoreMoviesHolder.imageLeft.hasFocus() ||
    // MoreMoviesHolder.imageRight.hasFocus()) {
    // Logs.logD("DEBUG_1", "THIS IS onKeyDown-->2");
    // MoreMoviesActivity.detailFocus = true;
    // mGridView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
    // index = 0;
    // if (mGridView.getChildAt(index) != null) {
    // mGridView.getChildAt(index).requestFocus();
    // }
    // return true;
    // }
    // if (MoreMoviesActivity.detailFocus == true) {
    // Logs.logD("DEBUG_1", "THIS IS onKeyDown--test>1" + index);
    // if (PagerData.size() > index + 5) {
    // index = index + 5;
    // } else {
    // index = PagerData.size() - 1;
    // }
    //
    // return true;
    // }
    // break;
    // case KeyEvent.KEYCODE_DPAD_UP:
    // if (MoreMoviesActivity.detailFocus == true) {
    // Logs.logD("DEBUG_1", "THIS IS onKeyDown--test>1" + index);
    //
    // index = index - 5;
    // }
    // default:
    // break;
    // }
    // return false;
    //
    // }
    /*********************** end *****************************/

    /*********************** 方案二/三 *****************************/
    // for VerticalViewPager
    public static synchronized boolean onKeyDown(int pos, int keyCode, KeyEvent event) {

        // if (PagerData == null || PagerData.size() == 0) {
        // return true;
        // }

        mGridView = (GridView) list.get(pos).findViewById(R.id.gv_movies);
        mGridView.setTag(pos);

        switch (keyCode) {
        case KeyEvent.KEYCODE_DPAD_RIGHT:
            // gridView没有数据时候的焦点处理
            if (PagerData == null || PagerData.size() == 0) {
                MoreMoviesActivity.detailFocus = true;
                ((TextView) ((FrameLayout) MoreMoviesHolder.mListView.getChildAt(MoreMoviesHolder.mListView
                        .getSelectedItemPosition())).getChildAt(0)).setBackgroundResource(R.drawable.title_normal);
                return false;
            }
            if (!MoreMoviesActivity.detailFocus) {
                Logs.logD("DEBUG", "THIS IS onKeyDown-->0" + mGridView.hasFocus());
                MoreMoviesActivity.detailFocus = true;

                // 此处存在一个BUG如果快速移动title 然后按右键会出现焦点消失的现象,此主要在虚拟机中存在，实际设备很少出现
                // 可能是：1，Listview强占了焦点；2，右键动作早于此gridView的初始化
                // 解決办法1：不用Listview
                mGridView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
                mGridView.requestFocus();

                // MoreMoviesHolder.mListView.getViewTreeObserver().addOnGlobalLayoutListener(
                // new OnGlobalLayoutListener() {
                //
                // @Override
                // public void onGlobalLayout() {
                // // TODO Auto-generated method stub
                //
                // }
                // });

                return true;
            }

            break;

        case KeyEvent.KEYCODE_DPAD_LEFT:
            if (mGridView.findFocus() != null && isLeftView()) {
                Logs.logD("DEBUG_1", "THIS IS onKeyDown-->KEYCODE_DPAD_LEFT");
                MoreMoviesActivity.detailFocus = false;
                mGridView.setDescendantFocusability(GridView.FOCUS_BLOCK_DESCENDANTS);
                mGridView.clearFocus();
            }
            break;

        case KeyEvent.KEYCODE_DPAD_DOWN:
            if (MoreMoviesHolder.imageLeft.hasFocus() || MoreMoviesHolder.imageRight.hasFocus()) {
                Logs.logD("DEBUG_1", "THIS IS onKeyDown-->2");
                mGridView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
                mGridView.requestFocus();
                return true;

            } else
            // 到达页面底部刷新页面后面的数据
            if (MoreMoviesActivity.detailFocus && isbottomView()) {
                if (pageNo < countPage) {
                    pageNo++;
                    refreshLoadData(posSelect, mlistData.get(posSelect).getId(), pageNo, NUMPERPAGE);
                }

            }
            break;
        case KeyEvent.KEYCODE_DPAD_UP:
        default:
            break;

        }
        return false;

    }

    /*********************** end *****************************/

    private static boolean isLeftView() {
        for (int i = 0; i < (((PagerData.size() - 1) / 5) + 1); i++) {
            if (mGridView.getChildAt(5 * i) != null && mGridView.getChildAt(5 * i).hasFocus()) {
                return true;
            }
        }
        return false;
    }

    private static boolean isbottomView() {
        for (int i = PagerData.size() - 1; i >= (pageNo * pageRow - 5); i--) {
            if (mGridView.getChildAt(i) != null && mGridView.getChildAt(i).hasFocus()) {
                return true;
            }
        }
        return false;
    }
}
